package com.panopset.swing;


import static com.panopset.UtilIO.createFileFromDirectory;
import static com.panopset.UtilIO.loadFile;
import static com.panopset.UtilIO.loadLinesFromTextResource;

import java.io.File;
import java.util.Vector;

import com.panopset.gui.DocumentNamer;
import com.panopset.io.LockedWriter;

/**
 * Application document. May have a default resource.
 *
 * @author Karl Dinwiddie
 *
 */
public abstract class Document {

    /**
     * Is loaded.
     */
    private boolean isLoaded = false;

    /**
     * @return Is loaded.
     */
    protected final boolean isLoaded() {
        return isLoaded;
    }

    /**
     * Load document from data.
     *
     * @param v
     *            Vector of Strings to load from.
     */
    protected abstract void load(final Vector<String> v);

    /**
     * Get document data to save.
     *
     * @return Vector of Strings to save.
     */
    protected abstract Vector<String> save();

    /**
     * File name.
     */
    private final DocumentNamer dn;

    /**
     * @return Document name.
     */
    public final String getDocumentName() {
        return dn.getName();
    }

    /**
     * @param documentNamer
     *            Document namer.
     */
    public Document(final DocumentNamer documentNamer) {
        App.app.s.registerDocument(this);
        dn = documentNamer;
    }

    /**
     * Load document from a directory.
     *
     * @param directory
     *            Directory.
     */
    public final void load(final File directory) {
        isLoaded = true;
        File f = createFileFromDirectory(directory, dn.getName());
        if (f.exists()) {
            Vector<String> v = loadFile(f);
            if (!v.isEmpty()) {
                load(v);
                return;
            }
        }
        load(loadLinesFromTextResource(dn.getDocumentClass(), dn.getName()));
    }

    /**
     * Save document to a directory.
     *
     * @param directory
     *            Directory.
     */
    public final void save(final File directory) {
        File f = createFileFromDirectory(directory, dn.getName());
        LockedWriter lw = new LockedWriter(f);
        for (String s : save()) {
            lw.writeln(s);
        }
        lw.close();
    }
}
